import {messages} from "share/common";
import React from 'react'
import {connect} from 'react-redux'
import constants from 'share/constants'
import {Button, Form, Switch, Input, Checkbox, Radio, InputNumber, Row, Col, message, Spin, Alert, Tooltip, Icon, Select} from 'antd'

const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;
const Option = Select.Option;
const {TextArea} = Input;
const FormItem = Form.Item;
import LanguageInput from 'components/template/language-input/language-input'
import PermissionsAllocation from 'components/template/permissions-allocation'
import ExpenseAllocation from 'containers/setting/form/form-detail/expense-allocation/expense-allocation'
import formService from 'containers/setting/form/form.service'
import menuRoute from 'routes/menuRoute'
import Chooser from 'components/chooser'
import errorMessage from 'share/errorMessage'

class FormDetailBase extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      form: {
        formName: '',
        remark: '',
        formNameI18n: null,
        remarkI18n: null
      },
      associateExpenseReport: {
        fetched: false,
        data: {}
      },
      //可关联的申请单范围
      //1001费用申请单
      //1002差旅申请单
      //1003费用申请单或者差旅申请单
      //配置都是字符串类型
      applicationOption: [
        {
          label: messages('setting.key586'/*费用申请单*/),//费用申请单
          value: '1001'
        },
        {
          label: messages('setting.key587'/*差旅申请单*/),//差旅申请单
          value: '1002'
        }
      ],
      outApplicationAmount: true,//借款金额小于等于申请金额
      isAutoLoan: false, //创建申请单时是否同时创建借款单
      autoLoanLoading: false,
      autoLoanList: [], //创建申请单时可同时创建的借款单，length为1，单选
      isReference: false,//关联申请单是否必选
      isHasLoanRelated: false,//是否开启借款单关联申请单的配置
      isExistLoanRelated: false,//是否有借款单关联申请单的配置
      relatedApplicationType: null, //借款单关联申请单的老配置上的applicationType字段
      relatedFormLoading: false,
      relatedFormList: [], //借款单关联申请单配置的可关联的表单
      withSubsidies: false, //是否添加补贴费用
      withTime: false, //是否启用时间
      newOthersSubsidy: false, //是否添加他人差补
      notShowItinerary: false, //是否不显示大行程
      selectedFormList: [], //补贴费用配置的差旅单
      isBudgetEr: false, //报销单提交时是否占用预算
      isBudgetCa: false, //申请单提交时是否占用预算
      isImportData: false, //报销单是否可导入结算数据
      isDeliverOther: false, //差旅，费用申请单是否转交给他人
      createOtherExpense: false, //差旅，费用报销单是否新建他人费用
      isMultiLine: false, //差旅，日常，费用报销单是否开启多付款行
      addVenMaster: false, //差旅，日常，费用报销单开启多付款行的情况下，是否允许新增供应商
      isLoanRelatedMore: 'Y', //差旅|费用申请单是否可被借款单关联多次，null & Y表示多次，N表示一次
      isRelatedMore: 'Y', //差旅|费用申请单是否可被报销多次，null & Y表示多次，N表示一次
      isRelatedNum: 'N', //差旅|费用申请单可被报销关联数量，null & N表示一张，Y表示多张
      controlDimesion: [], //超申请管控类型 1001总金额，1002费用类型，1003分摊行管控
      overflowProportion: 0, //超申请管控允许超额百分之几
      isForce: 0, //超申请管控力度 0警告 1禁止
      paymentTypeList: [], //付款方式下拉列表选择项
      payVisibleScope: 1001, //付款用途选择范围
      paySelectedList: [], //付款用途为部分类型是，选中的现金事务类型
      payDefaultSelectedList: [], //默认的现金事务类型
      contractEnable: false, //是否关联合同
      contractLocationList: [], //合同布局位置可选列表
      saving: false
    }
  }


  componentWillMount() {
    const {form, userScope, expenseTypeScope} = this.context;
    if (form) {
      this.initPayUses();
      if (form.associateExpenseReport) {
        formService.getFormDetail(form.referenceOID).then(res => {
          this.setState({
            associateExpenseReport: {
              fetched: true,
              data: res.data
            }
          })
        })
      }
      let formNameI18n = [], remarkI18n = [];
      if (form.i18n) {
        if (form.i18n.formName) {
          formNameI18n = form.i18n.formName;
        }
        if (form.i18n.remark) {
          remarkI18n = form.i18n.remark;
        }
      }
      form.formNameI18n = formNameI18n;
      form.remarkI18n = remarkI18n;
      this.setState({form});
    }
    this.initPaymentTypeList();
    this.initContactLocation();
  }

  initPaymentTypeList = () => {
    //只查询启用的
    formService.getSystemValueList(2105, true).then(resp => {
      let paymentTypeList = [];
      resp.data && resp.data.map(item => {
        paymentTypeList.push({key: item.value, label: item.messageKey});
      });
      this.setState({paymentTypeList});
    });
  };

  //初始化付款用途配置
  initPayUses = () => {
    const { form } = this.context;
    formService.getPayUses(form.formOID).then(res => {
      let payVisibleScope = res.data.visibleScope;
      let paySelectedList = res.data.loanTypes ? res.data.loanTypes : [];
      let payDefaultSelectedList = res.data.defaultLoanType ? [res.data.defaultLoanType] : [];
      this.setState({payVisibleScope, paySelectedList, payDefaultSelectedList});
    });
  };

  initContactLocation = () => {
    formService.getContactLocation().then(res => {
      this.setState({contractLocationList: res.data ? res.data : []});
    });
  };

  componentDidMount() {
    const {form, formType, propertyList} = this.context;
    const {tenantMode, company} = this.props;
    if (formType === 2005 || formType === 2006 || formType === 3001 || formType === 3002 || formType === 3003 || formType === 2001 || formType === 2002) {
      propertyList.map(property => {
        if (property.propertyName == 'loan.application.participation.repay.enable')
          this.props.form.setFieldsValue({associatePayExpense: property.propertyValue === 'true'});
        if (property.propertyName == 'loan.bill.pay.type')
          this.props.form.setFieldsValue({paymentType: property.propertyValue});

        if (property.propertyName == 'loan.application.configuration') {
          let loanConfiguration = JSON.parse(property.propertyValue);
          if (loanConfiguration.applicationFormOID && loanConfiguration.applicationFormOID.length) {
            //过滤启用，封装成控件可识别的数据格式
            this.setState({relatedFormLoading: true});
            formService.getFormIsEnable(loanConfiguration.applicationFormOID).then(res => {
              this.setState({relatedFormLoading: false});
              if (res.data && res.data.length) {
                let relatedFormList = [];
                res.data.map(relatedForm => {
                  relatedFormList.push({formName: relatedForm.formName, formOID: relatedForm.formOID});
                });
                this.setState({relatedFormList: relatedFormList});
              }
            });
          }
          this.setState({
            outApplicationAmount: loanConfiguration.outApplicationAmount,
            isReference: loanConfiguration.isReference,
            relatedApplicationType: loanConfiguration.applicationType ? loanConfiguration.applicationType : null,
            isExistLoanRelated: true,
            isHasLoanRelated: true
          });
        }
        if (property.propertyName === 'report.subsidy.config') {
          let expenseConfig = JSON.parse(property.propertyValue);
          this.setState({
            withSubsidies: expenseConfig.withSubsidies,
            withTime: expenseConfig.withTime ? expenseConfig.withTime : false,
            notShowItinerary: expenseConfig.notShowItinerary ? expenseConfig.notShowItinerary : false,
            newOthersSubsidy: expenseConfig.newOthersSubsidy ? expenseConfig.newOthersSubsidy : false,
            selectedFormList: expenseConfig.formOID ? [{formOID: expenseConfig.formOID}] : []
          });
        }
        if (property.propertyName === 'document.overapplication') {
          let overApplicationConfig = JSON.parse(property.propertyValue);
          this.setState({
            overflowProportion: overApplicationConfig.overflowProportion,
            isForce: overApplicationConfig.isForce,
            controlDimesion: overApplicationConfig.controlDimesion ? overApplicationConfig.controlDimesion : []
          });
        }
        if (property.propertyName === 'budget.er.enabled') {
          if (formType === 3001 || formType === 3002 || formType === 3003) {
            this.setState({
              isBudgetEr: property.propertyValue === 'true'
            });
          }
          if (formType === 2001 || formType === 2002) {
            this.setState({
              isBudgetCa: property.propertyValue === 'true'
            });
          }
        }
        if (property.propertyName === 'from.travel.relevance.application' || property.propertyName === 'from.expense.relevance.application') {
          this.setState({
            isRelatedMore: (!property.propertyValue || property.propertyValue === 'Y') ? 'Y' : 'N'
          });
        }
        if (property.propertyName === 'from.application.relevance.loan') {
          this.setState({
            isLoanRelatedMore: (!property.propertyValue || property.propertyValue === 'Y') ? 'Y' : 'N'
          });
        }
        if (property.propertyName === 'application.property.deliver.others') {
          this.setState({
            isDeliverOther: property.propertyValue === 'true'
          });
        }
        if (property.propertyName === 'report.property.create.others.expense') {
          this.setState({
            createOtherExpense: property.propertyValue === 'true'
          });
        }
        if (property.propertyName === 'report.property.pay.multi.lines') {
          this.setState({
            isMultiLine: property.propertyValue === 'true'
          });
        }
        if (property.propertyName === 'reimb.venmasteradd.enable') {
          this.setState({
            addVenMaster: property.propertyValue === 'true'
          });
        }
        if (property.propertyName === 'application.property.related.mutil.applications') {
          this.setState({
            isRelatedNum: property.propertyValue === 'Y' ? 'Y' : 'N'
          });
        }
        if (property.propertyName === 'application.direct.loan.enabled') {
          this.setState({
            isAutoLoan: property.propertyValue === 'true'
          });
        }
        if (property.propertyName == 'application.direct.loan.type' && property.propertyValue) {
          //过滤权限满足的，账套级分配的是否还存在以及获取表单名称
          let params = {
            formOIDs: [property.propertyValue],
            companyOID: !tenantMode ? company.companyOID : undefined
          };
          this.setState({autoLoanLoading: true});
          formService.getFormIsAutoLoan(params).then(res => {
            this.setState({autoLoanLoading: false});
            if (res.data && res.data.length) {
              let autoLoanList = [];
              res.data.map(relatedForm => {
                autoLoanList.push({formName: relatedForm.formName, formOID: relatedForm.formOID});
              });
              this.setState({autoLoanList});
            }
          });
        }
        if (property.propertyName === 'report.property.associated.contract.enabled' ||
          property.propertyName === 'loan.property.associated.contract.enabled') {
          this.setState({
            contractEnable: property.propertyValue === 'true'
          });
        }
        if (property.propertyName === 'report.property.associated.contract.config') {
          this.props.form.setFieldsValue({contractLocation: property.propertyValue});
        }
        if (property.propertyName === 'import.unify.data') {
          this.setState({
            isImportData: property.propertyValue === 'true'
          });
        }
      })
    }
    if (form) {
      this.props.form.setFieldsValue({
        valid: form.valid,
        formName: form.formName,
        formCode: form.formCode,
        sequence: form.sequence,
        remark: form.remark,
        isOfficialCard: Number(form.isOfficialCard) // 1: 公务卡，0：现金, 2:全部
      });
    }
  }

  handleNew = (values) => {
    let { formType, booksID } = this.context;
    let { form, outApplicationAmount, isReference, isHasLoanRelated, isExistLoanRelated, withSubsidies, selectedFormList,
      withTime, relatedFormList, isRelatedMore, isDeliverOther, createOtherExpense, newOthersSubsidy, isMultiLine,
      isRelatedNum, addVenMaster, isAutoLoan, autoLoanList, isBudgetCa, controlDimesion, overflowProportion, isForce,
      payVisibleScope, paySelectedList, payDefaultSelectedList, contractEnable, isBudgetEr, isImportData, isLoanRelatedMore,
      notShowItinerary
    } = this.state;
    let newForm = {
      asSystem: false,
      formType,
      customFormFields: [],
      iconName: '',
      language: this.props.language.code,
      ...form,
      ...values
    };
    let isOfficialCard = newForm.isOfficialCard;
    newForm.isOfficialCard = Number(isOfficialCard);
    this.processValue(newForm);
    if (this.validateLength(newForm)) {
      return;
    }
    if ((formType === 2001 || formType === 2002) && isAutoLoan && !autoLoanList.length) {
      message.error(messages('setting.key1760')/*请选择需要同时创建的借款单*/);
      return;
    }
    //差旅，费用申请单开启占预算，就必须勾选超申请管控类型
    if ((formType === 2001 || formType === 2002) && isBudgetCa && !controlDimesion.length) {
      message.error(messages('setting.key1842')/*请勾选管控类型*/);
      return;
    }
    if ((formType === 2005 || formType === 2006) && isHasLoanRelated && !relatedFormList.length) {
      message.error(messages('setting.key588'/*请选择关联的申请单*/));//请选择关联的申请单
      return;
    }
    if ((formType === 3001 || formType === 3002 || formType === 3003) && !(form.fromType === 2 && !this.props.tenantMode) && withSubsidies && !selectedFormList.length) {
      message.error(messages('setting.key589'/*请选择差补规则*/));
      return;
    }
    if (formType === 3001 || formType === 3002 || formType === 3003) {
      if (payVisibleScope === 1002 && !paySelectedList.length) {
        message.error(messages('setting.key1881')/*请选择付款用途*/);
        return;
      }
      if (!payDefaultSelectedList.length) {
        message.error(messages('setting.key1882')/*请选择付款用途默认值*/);
        return;
      }
      if (payVisibleScope === 1002 && !this.isContainDefaultPay()) {
        message.error(messages('setting.key1883')/*默认值需包含于已选择的部分类型*/);
        return;
      }
      if (contractEnable && !isMultiLine) {
        message.error(messages('setting.key1884')/*关联合同请开启多付款行!*/);
        return;
      }
    }
    this.setState({saving: true});
    formService.newFormDetail(newForm).then(res => {
      let serviceArray = [];
      if (formType === 2001 || formType === 2002) {
        let applicationRelatedList = [];
        let applicationRelatedNum = {};//申请单可被报销几次
        applicationRelatedNum.formOID = res.data.formOID;
        applicationRelatedNum.propertyName = formType === 2001 ? 'from.travel.relevance.application' : 'from.expense.relevance.application';
        applicationRelatedNum.propertyValue = isRelatedMore;
        applicationRelatedList.push(applicationRelatedNum);
        let applicationLoanRelatedNum = {};//申请单可被借款单关联几次
        applicationLoanRelatedNum.formOID = res.data.formOID;
        applicationLoanRelatedNum.propertyName = 'from.application.relevance.loan';
        applicationLoanRelatedNum.propertyValue = isLoanRelatedMore;
        applicationRelatedList.push(applicationLoanRelatedNum);
        let applicationRelated = {};//申请单可被报销单关联的数量
        applicationRelated.formOID = res.data.formOID;
        applicationRelated.propertyName = 'application.property.related.mutil.applications';
        applicationRelated.propertyValue = isRelatedNum;
        applicationRelatedList.push(applicationRelated);
        let deliverOther = {};
        deliverOther.formOID = res.data.formOID;
        deliverOther.propertyName = 'application.property.deliver.others';
        deliverOther.propertyValue = isDeliverOther;
        applicationRelatedList.push(deliverOther);
        let autoLoan = {};
        autoLoan.formOID = res.data.formOID;
        autoLoan.propertyName = 'application.direct.loan.enabled';
        autoLoan.propertyValue = isAutoLoan;
        applicationRelatedList.push(autoLoan);
        let autoLoanForm = {};
        autoLoanForm.formOID = res.data.formOID;
        autoLoanForm.propertyName = 'application.direct.loan.type';
        autoLoanForm.propertyValue = autoLoanList.length ? autoLoanList[0].formOID : '';
        applicationRelatedList.push(autoLoanForm);
        let overApplication = {};
        overApplication.formOID = res.data.formOID;
        overApplication.propertyName = 'document.overapplication';
        let overApplicationValue = {
          isForce,
          overflowProportion,
          controlDimesion: controlDimesion.length ? controlDimesion : []
        };
        overApplication.propertyValue = JSON.stringify(overApplicationValue);
        applicationRelatedList.push(overApplication);
        serviceArray.push(formService.saveFormProperty(applicationRelatedList));
      }
      if (formType === 2005 || formType === 2006) {
        let loanPropertyList = [];
        let repayType = {};
        repayType.formOID = res.data.formOID;
        repayType.propertyName = 'loan.bill.pay.type';
        repayType.propertyValue = values.paymentType;
        loanPropertyList.push(repayType);
        let repayEnable = {};
        repayEnable.formOID = res.data.formOID;
        repayEnable.propertyName = 'loan.application.participation.repay.enable';
        repayEnable.propertyValue = values.associatePayExpense + '';
        loanPropertyList.push(repayEnable);
        let contractConfig01 = {};
        contractConfig01.formOID = res.data.formOID;
        contractConfig01.propertyName = 'loan.property.associated.contract.enabled';
        contractConfig01.propertyValue = contractEnable;
        loanPropertyList.push(contractConfig01);
        let loanRelate = {};
        loanRelate.formOID = res.data.formOID;
        loanRelate.propertyName = 'loan.application.configuration';
        let relatedFormOIDList = [];
        relatedFormList.map(relatedForm => {
          relatedFormOIDList.push(relatedForm.formOID);
        });
        loanRelate.propertyValue = JSON.stringify({
          outApplicationAmount: outApplicationAmount,
          isReference: isReference,
          applicationFormOID: relatedFormOIDList
        });
        if (isHasLoanRelated) {
          loanPropertyList.push(loanRelate);
        }
        serviceArray.push(formService.saveFormProperty(loanPropertyList));
        //删除借款单关联申请单的表单配置
        if (!isHasLoanRelated && isExistLoanRelated) {
          serviceArray.push(formService.removeFormProperty(res.data.formOID, ['loan.application.configuration']));
        }
      }
      let expensePropertyList = [];
      if (formType === 3002 || formType === 3003) {
        let createOtherExpenseConfig = {};
        createOtherExpenseConfig.formOID = res.data.formOID;
        createOtherExpenseConfig.propertyName = 'report.property.create.others.expense';
        createOtherExpenseConfig.propertyValue = createOtherExpense;
        expensePropertyList.push(createOtherExpenseConfig);
      }
      if (formType === 3001 || formType === 3002 || formType === 3003) {
        let repayType = {};
        repayType.formOID = res.data.formOID;
        repayType.propertyName = 'loan.bill.pay.type';
        repayType.propertyValue = values.paymentType;
        expensePropertyList.push(repayType);
        let contractConfig01 = {};
        contractConfig01.formOID = res.data.formOID;
        contractConfig01.propertyName = 'report.property.associated.contract.enabled';
        contractConfig01.propertyValue = contractEnable;
        expensePropertyList.push(contractConfig01);
        let contractConfig02 = {};
        contractConfig02.formOID = res.data.formOID;
        contractConfig02.propertyName = 'report.property.associated.contract.config';
        contractConfig02.propertyValue = values.contractLocation;
        expensePropertyList.push(contractConfig02);
        let multiErConfig = {};
        multiErConfig.formOID = res.data.formOID;
        multiErConfig.propertyName = 'report.property.pay.multi.lines';
        multiErConfig.propertyValue = isMultiLine;
        expensePropertyList.push(multiErConfig);
        let venMasterErConfig = {};
        venMasterErConfig.formOID = res.data.formOID;
        venMasterErConfig.propertyName = 'reimb.venmasteradd.enable';
        venMasterErConfig.propertyValue = addVenMaster;
        expensePropertyList.push(venMasterErConfig);
        let budgetErConfig = {};
        budgetErConfig.formOID = res.data.formOID;
        budgetErConfig.propertyName = 'budget.er.enabled';
        budgetErConfig.propertyValue = isBudgetEr;
        expensePropertyList.push(budgetErConfig);
        let isImportDataConfig = {};
        isImportDataConfig.formOID = res.data.formOID;
        isImportDataConfig.propertyName = 'import.unify.data';
        isImportDataConfig.propertyValue = isImportData;
        expensePropertyList.push(isImportDataConfig);
      }
      if ((formType === 3001 || formType === 3002 || formType === 3003) && !(form.fromType === 2 && !this.props.tenantMode)) {
        let subsidiesConfig = {};
        let subsidiesConfigValue = {};
        subsidiesConfig.formOID = res.data.formOID;
        subsidiesConfig.propertyName = 'report.subsidy.config';
        subsidiesConfigValue.withSubsidies = withSubsidies;
        if (withSubsidies) {
          subsidiesConfigValue.withTime = withTime;
          subsidiesConfigValue.notShowItinerary = notShowItinerary;
          if (selectedFormList && selectedFormList.length) {
            subsidiesConfigValue.formOID = selectedFormList[0].formOID;
          }
        }
        if ((formType === 3002 || formType === 3003) && withSubsidies) {
          subsidiesConfigValue.newOthersSubsidy = newOthersSubsidy;
        }
        subsidiesConfig.propertyValue = JSON.stringify(subsidiesConfigValue);
        expensePropertyList.push(subsidiesConfig);
      }
      if (formType === 3001 || formType === 3002 || formType === 3003) {
        serviceArray.push(formService.savePayUses(this.processPayUsesParams(res.data.formOID)));
      }
      if (expensePropertyList.length) {
        serviceArray.push(formService.saveFormProperty(expensePropertyList));
      }
      Promise.all(serviceArray).then(response => {
        message.success(messages("common.save.success", {name: res.data.formName}));
        this.setState({saving: false});
        let redirect_url = menuRoute.getRouteItem('form-detail').url.replace(':formOID', res.data.formOID);
        if (booksID && booksID !== ':booksID') {
          redirect_url = redirect_url.replace(':booksID', booksID);
        }
        this.context.router.replace(redirect_url);
        this.props.handleNew(res.data);
      }).catch(e => {
        let error = e.response.data;
        if (error.validationErrors && error.validationErrors.length) {
          message.error(`${messages('common.save.filed')}，${error.validationErrors[0].message}`)
        } else {
          message.error(`${messages('common.save.filed')}，${error.message}`)
        }
        this.setState({saving: false});
      });
    }).catch(err => {
      errorMessage(err.response);
      this.setState({saving: false});
    });
  };

  //付款用途选择部分类型时，默认值需要包含在所选类型中
  isContainDefaultPay = () => {
    const { paySelectedList, payDefaultSelectedList } = this.state;
    let defaultItem = payDefaultSelectedList[0];
    let isContain = false;
    paySelectedList.map(selected => {
      if (selected.id === defaultItem.id) {
        isContain = true;
      }
    });
    return isContain;
  };

  //处理付款用途params
  processPayUsesParams = (formOID) => {
    const { payVisibleScope, paySelectedList, payDefaultSelectedList } = this.state;
    let params = {};
    params.entityOID = formOID;
    params.visibleScope = payVisibleScope;
    params.loanTypeIds = [];
    paySelectedList.map(selected => {
      params.loanTypeIds.push(selected.id);
    });
    params.defaultLoanTypeId = payDefaultSelectedList[0].id;
    return params;
  };

  //新建／保存前处理数据
  processValue = (formData) => {
    const { isBudgetCa } = this.state;
    let {booksID} = this.context;
    formData.budgetEnabled = isBudgetCa;
    if (booksID && booksID !== ':booksID') {
      formData.booksID = booksID;
    }
    if (formData.associateExpenseReport) {
      formData.associateExpenseReport = true;
    } else {
      formData.associateExpenseReport = false;
    }
    if (this.props.tenantMode) {
      formData.fromType = 2;
    } else {
      formData.fromType = 1;
    }
    formData.i18n = {};
    if (formData.formNameI18n) {
      let formNameLanguageList = [];
      formData.formNameI18n.map((item) => {
        if (item.language === 'zh_cn') {
          item.language = 'zh_CN';
        }
        formNameLanguageList.push(item.language);
      });
      //没有的语言value初始化个''
      this.props.languageList.map((languageItem) => {
        if (formNameLanguageList.indexOf(languageItem.code) === -1) {
          formData.formNameI18n.push({
            language: languageItem.code,
            value: ''
          })
        }
      });
      formData.i18n.formName = formData.formNameI18n;
    }
    if (formData.remarkI18n) {
      let remarkLanguageList = [];
      formData.remarkI18n.map((item) => {
        if (item.language === 'zh_cn') {
          item.language = 'zh_CN';
        }
        remarkLanguageList.push(item.language);
      });
      //没有的语言value初始化个''
      this.props.languageList.map((languageItem) => {
        if (remarkLanguageList.indexOf(languageItem.code) === -1) {
          formData.remarkI18n.push({
            language: languageItem.code,
            value: ''
          })
        }
      });
      formData.i18n.remark = formData.remarkI18n;
    }
  };

  //新建／保存前校验多语言长度
  validateLength = (formData) => {
    let isOverLength = false; //是否超过字符长度
    let errorMessage = '';
    if (formData.i18n.formName) {
      formData.i18n.formName.map(item => {
        if (item.value && item.value.length > 50) {
          errorMessage = messages("common.max.characters.length", {max: 50});
          isOverLength = true;
        }
      });
    }
    if (formData.i18n.remark) {
      formData.i18n.remark.map(item => {
        if (item.value && item.value.length > 50) {
          errorMessage = messages("common.max.characters.length", {max: 50});
          isOverLength = true;
        }
      });
    }
    if (isOverLength) {
      message.error(errorMessage);
    }
    return isOverLength;
  };

  handleSave = (e) => {
    e.preventDefault();
    let { form, formOID, formType } = this.context;
    let { userValue, expenseTypeValue, visibleCompanyScope, companySelectedList, outApplicationAmount, isReference,
      isHasLoanRelated, isExistLoanRelated, withSubsidies, selectedFormList, withTime, isBudgetEr, relatedFormList,
      relatedApplicationType, isRelatedMore, isDeliverOther, createOtherExpense, newOthersSubsidy, isMultiLine,
      isRelatedNum, addVenMaster, isAutoLoan, autoLoanList, isBudgetCa, controlDimesion, overflowProportion,
      isForce, payVisibleScope, paySelectedList, payDefaultSelectedList, contractEnable, isImportData, isLoanRelatedMore,
      notShowItinerary
    } = this.state;

    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (form) {
          let serviceArray = [];
          form.i18n = {
            formName: form.formNameI18n,
            remark: form.remarkI18n
          };
          form.valid = values.valid;
          form.isOfficialCard = Number(values.isOfficialCard);
          form.sequence = values.sequence;
          form.formCode = values.formCode;
          if (formType === 2001 || formType === 2002) {
            if (isAutoLoan && !autoLoanList.length) {
              message.error(messages('setting.key1760')/*请选择需要同时创建的借款单*/);
              return;
            }
            //差旅，费用申请单开启占预算，就必须勾选超申请管控类型
            if (isBudgetCa && !controlDimesion.length) {
              message.error(messages('setting.key1842')/*请勾选管控类型*/);
              return;
            }
            let applicationRelatedList = [];
            let applicationRelatedNum = {};//申请单可被报销几次
            applicationRelatedNum.formOID = form.formOID;
            applicationRelatedNum.propertyName = formType === 2001 ? 'from.travel.relevance.application' : 'from.expense.relevance.application';
            applicationRelatedNum.propertyValue = isRelatedMore;
            applicationRelatedList.push(applicationRelatedNum);
            let applicationLoanRelatedNum = {};//申请单可被借款单关联几次
            applicationLoanRelatedNum.formOID = form.formOID;
            applicationLoanRelatedNum.propertyName = 'from.application.relevance.loan';
            applicationLoanRelatedNum.propertyValue = isLoanRelatedMore;
            applicationRelatedList.push(applicationLoanRelatedNum);
            let applicationRelated = {};//申请单可被报销单关联的数量
            applicationRelated.formOID = form.formOID;
            applicationRelated.propertyName = 'application.property.related.mutil.applications';
            applicationRelated.propertyValue = isRelatedNum;
            applicationRelatedList.push(applicationRelated);
            let deliverOther = {};
            deliverOther.formOID = form.formOID;
            deliverOther.propertyName = 'application.property.deliver.others';
            deliverOther.propertyValue = isDeliverOther;
            applicationRelatedList.push(deliverOther);
            let autoLoan = {};
            autoLoan.formOID = form.formOID;
            autoLoan.propertyName = 'application.direct.loan.enabled';
            autoLoan.propertyValue = isAutoLoan;
            applicationRelatedList.push(autoLoan);
            let autoLoanForm = {};
            autoLoanForm.formOID = form.formOID;
            autoLoanForm.propertyName = 'application.direct.loan.type';
            autoLoanForm.propertyValue = autoLoanList.length ? autoLoanList[0].formOID : '';
            applicationRelatedList.push(autoLoanForm);
            let overApplication = {};
            overApplication.formOID = form.formOID;
            overApplication.propertyName = 'document.overapplication';
            let overApplicationValue = {
              isForce,
              overflowProportion,
              controlDimesion: controlDimesion.length ? controlDimesion : []
            };
            overApplication.propertyValue = JSON.stringify(overApplicationValue);
            applicationRelatedList.push(overApplication);
            serviceArray.push(formService.saveFormProperty(applicationRelatedList));
          }
          if (formType === 2005 || formType === 2006) {
            if (isHasLoanRelated && !relatedFormList.length) {
              message.error(messages('setting.key588'/*请选择关联的申请单*/));//请选择关联的申请单类型
              return;
            }
            let loanPropertyList = [];
            let repayType = {};
            repayType.formOID = form.formOID;
            repayType.propertyName = 'loan.bill.pay.type';
            repayType.propertyValue = values.paymentType;
            loanPropertyList.push(repayType);
            let repayEnable = {};
            repayEnable.formOID = form.formOID;
            repayEnable.propertyName = 'loan.application.participation.repay.enable';
            repayEnable.propertyValue = values.associatePayExpense + '';
            loanPropertyList.push(repayEnable);
            let contractConfig01 = {};
            contractConfig01.formOID = form.formOID;
            contractConfig01.propertyName = 'loan.property.associated.contract.enabled';
            contractConfig01.propertyValue = contractEnable;
            loanPropertyList.push(contractConfig01);
            let loanRelate = {};
            loanRelate.formOID = form.formOID;
            loanRelate.propertyName = 'loan.application.configuration';
            let relatedFormOIDList = [];
            relatedFormList.map(relatedForm => {
              relatedFormOIDList.push(relatedForm.formOID);
            });
            let loanRelateValue = {
              outApplicationAmount: outApplicationAmount,
              isReference: isReference,
              applicationFormOID: relatedFormOIDList
            };
            if (relatedApplicationType) {
              loanRelateValue.applicationType = relatedApplicationType;
            }
            loanRelate.propertyValue = JSON.stringify(loanRelateValue);
            if (isHasLoanRelated) {
              loanPropertyList.push(loanRelate);
            }
            serviceArray.push(formService.saveFormProperty(loanPropertyList));
            //删除借款单关联申请单的表单配置
            if (!isHasLoanRelated && isExistLoanRelated) {
              serviceArray.push(formService.removeFormProperty(form.formOID, ['loan.application.configuration']));
            }
          }
          let expensePropertyList = [];
          if (formType === 3001 || formType === 3002 || formType === 3003) {
            if (payVisibleScope === 1002 && !paySelectedList.length) {
              message.error(messages('setting.key1881')/*请选择付款用途*/);
              return;
            }
            if (!payDefaultSelectedList.length) {
              message.error(messages('setting.key1882')/*请选择付款用途默认值*/);
              return;
            }
            if (payVisibleScope === 1002 && !this.isContainDefaultPay()) {
              message.error(messages('setting.key1883')/*默认值需包含于已选择的部分类型*/);
              return;
            }
            let budgetErConfig = {};
            budgetErConfig.formOID = form.formOID;
            budgetErConfig.propertyName = 'budget.er.enabled';
            budgetErConfig.propertyValue = isBudgetEr;
            expensePropertyList.push(budgetErConfig);
            let isImportDataConfig = {};
            isImportDataConfig.formOID = form.formOID;
            isImportDataConfig.propertyName = 'import.unify.data';
            isImportDataConfig.propertyValue = isImportData;
            expensePropertyList.push(isImportDataConfig);
          }
          if (formType === 3001 || formType === 3002 || formType === 3003) {
            if (contractEnable && !isMultiLine) {
              message.error(messages('setting.key1884')/*关联合同请开启多付款行!*/);
              return;
            }
            let repayType = {};
            repayType.formOID = form.formOID;
            repayType.propertyName = 'loan.bill.pay.type';
            repayType.propertyValue = values.paymentType;
            expensePropertyList.push(repayType);
            let contractConfig01 = {};
            contractConfig01.formOID = form.formOID;
            contractConfig01.propertyName = 'report.property.associated.contract.enabled';
            contractConfig01.propertyValue = contractEnable;
            expensePropertyList.push(contractConfig01);
            let contractConfig02 = {};
            contractConfig02.formOID = form.formOID;
            contractConfig02.propertyName = 'report.property.associated.contract.config';
            contractConfig02.propertyValue = values.contractLocation;
            expensePropertyList.push(contractConfig02);
            let multiErConfig = {};
            multiErConfig.formOID = form.formOID;
            multiErConfig.propertyName = 'report.property.pay.multi.lines';
            multiErConfig.propertyValue = isMultiLine;
            expensePropertyList.push(multiErConfig);
            let venMasterErConfig = {};
            venMasterErConfig.formOID = form.formOID;
            venMasterErConfig.propertyName = 'reimb.venmasteradd.enable';
            venMasterErConfig.propertyValue = addVenMaster;
            expensePropertyList.push(venMasterErConfig);
          }
          if (formType === 3002 || formType === 3003) {
            let createOtherExpenseConfig = {};
            createOtherExpenseConfig.formOID = form.formOID;
            createOtherExpenseConfig.propertyName = 'report.property.create.others.expense';
            createOtherExpenseConfig.propertyValue = createOtherExpense;
            expensePropertyList.push(createOtherExpenseConfig);
          }
          if ((formType === 3001 || formType === 3002 || formType === 3003) && !(form.fromType === 2 && !this.props.tenantMode)) {
            if (withSubsidies && !selectedFormList.length) {
              message.error(messages('setting.key589'/*请选择差补规则*/));
              return;
            }
            let subsidiesConfig = {};
            let subsidiesConfigValue = {};
            subsidiesConfig.formOID = form.formOID;
            subsidiesConfig.propertyName = 'report.subsidy.config';
            subsidiesConfigValue.withSubsidies = withSubsidies;
            if (withSubsidies) {
              subsidiesConfigValue.withTime = withTime;
              subsidiesConfigValue.notShowItinerary = notShowItinerary;
              if (selectedFormList && selectedFormList.length) {
                subsidiesConfigValue.formOID = selectedFormList[0].formOID;
              }
            }
            if ((formType === 3002 || formType === 3003) && withSubsidies) {
              subsidiesConfigValue.newOthersSubsidy = newOthersSubsidy;
            }
            subsidiesConfig.propertyValue = JSON.stringify(subsidiesConfigValue);
            expensePropertyList.push(subsidiesConfig);
          }
          if (expensePropertyList.length) {
            serviceArray.push(formService.saveFormProperty(expensePropertyList));
          }
          let result = {
            customFormDTO: form
          };
          this.processValue(result.customFormDTO);
          if (this.validateLength(result.customFormDTO)) {
            return;
          }
          this.setState({saving: true});
          serviceArray.push(formService.saveForm(result));
          Promise.all(serviceArray).then(res => {
            message.success(messages("common.save.success", {name: form.formName}));
            this.setState({saving: false});
            this.props.refreshBase(form.formOID);
            if (formType === 3001 || formType === 3002 || formType === 3003) {
              formService.savePayUses(this.processPayUsesParams(form.formOID)).then(response => {});
            }
          }).catch(e => {
            let error = e.response.data;
            if (error.validationErrors && error.validationErrors.length) {
              message.error(`${messages('common.save.filed')}，${error.validationErrors[0].message}`)
            } else {
              message.error(`${messages('common.save.filed')}，${error.message}`)
            }
            this.setState({ saving: false });
          });
        } else {
          this.handleNew(values);
        }
      }
    });
  };
  handleChangePermissions = (values) => {
    this.setState({userValue: values});
  };

  handleChangeExpense = (value) => {
    this.setState({expenseTypeValue: values});
  };

  handleLanguageInput = (name, i18n, attr) => {
    let {form} = this.state;
    form[attr] = name;
    form[attr + 'I18n'] = i18n;
    this.setState({form})
  };

  handleChangeCompany = (e) => {
    this.setState({
      visibleCompanyScope: e.target.value
    }, () => {
      this.setState({companySelectedList: []});
    });
  };

  handleSelectForm = (value, key) => {
    this.setState({
      [key]: value
    });
  };

  handleChangeCheckbox = (value, key) => {
    this.setState({
      [key]: value
    });
  };

  handleChangeAmount = (value, key) => {
    if (!isNaN(value) && value !== null && value !== undefined && value !== '') {
      this.setState({
        [key]: value
      });
    }
  };

  handleStatusChange = (value, key) => {
    const {formOID} = this.context;
    if (key === 'isBudgetCa' || key === 'isBudgetEr') {
      if (formOID) {
        let serviceName = key === 'isBudgetEr' ? 'getFormIsHasData' : 'getCaFormIsHasData';
        formService[serviceName](formOID).then(res => {
          if (res.data) {
            //有数据时不可更改配置
            message.error(messages('setting.key590'/*已有相应的业务数据，不可修改。*/));
          } else {
            //没有数据时可更改配置
            this.setState({
              [key]: value
            });
          }
        });
      } else {
        this.setState({
          [key]: value
        });
      }
    }
    if (key !== 'isBudgetEr' && key !== 'isBudgetCa') {
      this.setState({
        [key]: value
      });
    }
  };

  handleSelectTravelRule = (value) => {
    this.setState({selectedFormList: value});
  };

  render() {
    const { formType, formOID, booksID } = this.context;
    const { getFieldDecorator } = this.props.form;
    const { company } = this.props;
    const { form, saving, associateExpenseReport, applicationOption, outApplicationAmount, isReference, isHasLoanRelated,
      withSubsidies, selectedFormList, withTime, isBudgetEr, isBudgetCa, relatedFormList, relatedFormLoading, isRelatedMore,
      isDeliverOther, createOtherExpense, newOthersSubsidy, isMultiLine, isRelatedNum, addVenMaster, isAutoLoan,
      autoLoanLoading, autoLoanList, controlDimesion, overflowProportion, isForce, paymentTypeList,
      payVisibleScope, paySelectedList, payDefaultSelectedList, contractEnable, contractLocationList, isImportData,
      isLoanRelatedMore, notShowItinerary
    } = this.state;
    const formItemLayout = {
      labelCol: {span: 4},
      wrapperCol: {span: 8, offset: 1},
    };
    const formItemLayoutBig = {
      labelCol: {span: 4},
      wrapperCol: {span: 19, offset: 1},
    };
    return (
      <div className="form-detail-base">
        <Form onSubmit={this.handleSave}>
          <div className="info-title">{messages('setting.key591'/*基本信息*/)}</div>
          <FormItem {...formItemLayout} label={messages('setting.key592'/*类型*/)}>
            <span>{constants.getTextByValue(formType, 'documentTypeForShow')}</span>
          </FormItem>
          {form.associateExpenseReport && (
            <FormItem {...formItemLayout} label={messages('setting.key593'/*关联单据*/)}>
              <span>{associateExpenseReport.fetched ? associateExpenseReport.data.formName : <Spin/>}</span>
            </FormItem>
          )}
          <FormItem {...formItemLayout} label={messages('setting.key594'/*状态*/)}>
            {getFieldDecorator('valid', {
              valuePropName: 'checked',
              initialValue: true
            })(
              <Switch disabled={form.fromType == 2 && !this.props.tenantMode}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('mcd.setting.formManageBasic.isOfficialCard'/* 关联现金公务卡 */)}>
            {getFieldDecorator('isOfficialCard', {
              //valuePropName: 'checked',
              initialValue: undefined
            })(
              // <Switch disabled={form.fromType == 2 && !this.props.tenantMode}/>
              <Select
                  disabled={form.fromType == 2 && !this.props.tenantMode}
                  placeholder={messages('common.please.select')}
                  defaultActiveFirstOption={false}
                  showArrow={true}
                  getPopupContainer={triggerNode => triggerNode.parentNode}>
                  <Option key = '2' value={2}>{messages('mcd.setting.formManageBasic.isOfficialCard2')}</Option>
                  <Option key = '0' value={0}>{messages('mcd.setting.formManageBasic.isOfficialCard0')}</Option>
                  <Option key = '1' value={1}>{messages('mcd.setting.formManageBasic.isOfficialCard1')}</Option>
                </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key1843')/*表单编码*/}>
            {getFieldDecorator('formCode', {
              rules: [
                {
                  max: 50,
                  message: messages('common.max.characters.length', {max: 50})
                },
                {
                  required: true,
                  message: messages('common.please.enter')  //请输入
                },
                {
                  validator: (item, value, callback) => {
                    if(value && !value.match("^[0-9a-zA-Z_\-]*$")){
                      callback(messages('setting.key1869')/*只允许填写字母、数字、_或-*/);
                    }
                    callback();
                  }
                }
              ],
              initialValue: ''
            })(
              <Input type="text"
                     autoComplete="off"
                     placeholder={messages('common.please.enter')}
                     disabled={form.fromType == 2 && !this.props.tenantMode}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key595'/*表单名称*/)}>
            {getFieldDecorator('formName', {
              rules: [
                {
                  required: true,
                  message: messages('common.please.enter')  //请输入
                },
                {
                  max: 50,
                  message: messages('common.max.characters.length', {max: 50})
                }
              ],
              initialValue: ''
            })(
              <LanguageInput nameChange={(value, i18n) => this.handleLanguageInput(value, i18n, 'formName')}
                             width={'100%'}
                             name={form.formName}
                             placeholder={messages('common.max.characters.length', {max: 50})}
                             isEdit={formOID}
                             disabled={form.fromType == 2 && !this.props.tenantMode}
                             i18nName={form.formNameI18n}/>
            )}
            <div style={{color: '#989898'}}>{messages('setting.key596'/*名称可重复，请避免员工看到重名表单*/)}</div>
          </FormItem>
          <FormItem {...formItemLayout} label={(
            <span> {messages('setting.key227')/*顺序号*/}&nbsp;
              <Tooltip title={messages('setting.key1542')/*序号之间尽量保持一定的步长，便于后续调整*/}>
                <Icon type="question-circle-o" />
              </Tooltip>
            </span>
          )}>
            {getFieldDecorator('sequence', {
              rules: [
                {
                  required: true,
                  message: messages('common.please.enter')  //请输入
                }
              ],
              initialValue: 10
            })(
              <InputNumber style={{width: '100%'}} min={0} max={9999} precision={0}/>
            )}
            <div style={{color: '#989898'}}>{messages('setting.key1543')/*表单排序按顺序号由小到大排序*/}</div>
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key597'/*备注*/)}>
            {getFieldDecorator('remark', {
              rules: [
                {
                  required: true,
                  message: messages('common.please.enter')  //请输入
                },
                {
                  max: 50,
                  message: messages('common.max.characters.length', {max: 50})
                }
              ],
              initialValue: ''
            })(
              <LanguageInput nameChange={(value, i18n) => this.handleLanguageInput(value, i18n, 'remark')}
                             width={'100%'}
                             name={form.remark}
                             textArea={true}
                             placeholder={messages('common.max.characters.length', {max: 50})}
                             isEdit={formOID}
                             disabled={form.fromType == 2 && !this.props.tenantMode}
                             i18nName={form.remarkI18n}/>
            )}
          </FormItem>
          {(formType === 2001 || formType === 2002) && !formOID &&
          <div>
            <FormItem {...formItemLayout} label={messages('setting.key598'/*关联报销单*/)}>
              {getFieldDecorator('associateExpenseReport')(
                <Checkbox disabled={form.fromType == 2 && !this.props.tenantMode} defaultChecked={form && form.associateExpenseReport}>
                  {messages('setting.key599'/*关联*/)}<span className="associate-info">{messages('setting.key600'/*勾选后将自动生成对应报销单*/)}</span>
                </Checkbox>
              )}
            </FormItem>
          </div>
          }
          {([2005, 2006, 3001, 3002, 3003].indexOf(formType) > -1) && (
            <FormItem {...formItemLayout} label={messages('setting.key1544')/*付款方式类型*/}>
              {getFieldDecorator('paymentType', {
                rules: [
                  {
                    required: true,
                    message: messages('common.please.select')
                  }
                ],
                initialValue: undefined
              })(
                <Select
                  disabled={form.fromType == 2 && !this.props.tenantMode}
                  placeholder={messages('common.please.select')}
                  defaultActiveFirstOption={false}
                  showArrow={true}
                  getPopupContainer={triggerNode => triggerNode.parentNode}>
                  {paymentTypeList.map((option) => {
                    return <Option key={option.key}>{option.label}</Option>
                  })}
                </Select>
              )}
            </FormItem>
          )}
          {(formType === 3001 || formType === 3002 || formType === 3003) && (
            <div>
              <FormItem {...formItemLayout} label={messages('setting.key1885')/*付款用途*/}>
                <div>
                  <RadioGroup disabled={form.fromType == 2 && !this.props.tenantMode} value={payVisibleScope} onChange={e => this.handleChangeCheckbox(e.target.value, 'payVisibleScope')}>
                    <Radio value={1001}>{messages('common.all.type')/*全部类型*/}</Radio>
                    <Radio style={{marginLeft: 50}} value={1002}>{messages('setting.key1552')/*部分类型*/}</Radio>
                  </RadioGroup>
                </div>
                {payVisibleScope === 1002 && (
                  <Chooser placeholder={messages('common.please.select')}
                           type='payment_cash_type'
                           labelKey='description'
                           valueKey='id'
                           disabled={form.fromType == 2 && !this.props.tenantMode}
                           onChange={value => this.handleSelectForm(value, 'paySelectedList')}
                           value={paySelectedList}
                           listExtraParams={{
                             setOfBookId: booksID !== ':booksID' ? booksID : company.setOfBooksId, //借款这后台参数定义跟别的不一样，是setOfBookId，而不是setOfBooksId，醉了
                             typeCode: 'PAYMENT' //付款类型
                           }}
                           showNumber={true}
                           single={false}/>
                )}
                <Row style={{marginTop: 12}}>
                  <Col span={6}>
                    <span style={{fontSize: 14, color: '#f5222d', fontFamily: 'SimSun'}}>*&nbsp;</span> {messages('setting.key1886')/*默认值：*/}
                  </Col>
                  <Col span={18}>
                    <Chooser placeholder={messages('common.please.select')}
                             type='payment_cash_type'
                             labelKey='description'
                             valueKey='id'
                             disabled={form.fromType == 2 && !this.props.tenantMode}
                             onChange={value => this.handleSelectForm(value, 'payDefaultSelectedList')}
                             value={payDefaultSelectedList}
                             listExtraParams={{
                               setOfBookId: booksID !== ':booksID' ? booksID : company.setOfBooksId, //借款这后台参数定义跟别的不一样，是setOfBookId，而不是setOfBooksId，醉了
                               typeCode: 'PAYMENT' //付款类型
                             }}
                             showNumber={false}
                             single={true}/>
                  </Col>
                </Row>
              </FormItem>
              <FormItem {...formItemLayout} label={messages('setting.key1887')/*关联合同*/}>
                <div>
                  <RadioGroup disabled={form.fromType == 2 && !this.props.tenantMode} value={contractEnable} onChange={e => this.handleChangeCheckbox(e.target.value, 'contractEnable')}>
                    <Radio value={false}>{messages('common.no')/*否*/}</Radio>
                    <Radio style={{marginLeft: 50}} value={true}>{messages('common.yes')/*是*/}</Radio>
                  </RadioGroup>
                </div>
              </FormItem>
              {contractEnable && (
                <FormItem {...formItemLayout} label={messages('setting.key1888')/*合同布局位置*/}>
                  {getFieldDecorator('contractLocation', {
                    rules: [
                      {
                        required: true,
                        message: messages('common.please.select')
                      }
                    ],
                    initialValue: 'DOCUMENTS_HEAD'
                  })(
                    <Select
                      disabled={form.fromType == 2 && !this.props.tenantMode}
                      placeholder={messages('common.please.select')}
                      defaultActiveFirstOption={false}
                      showArrow={true}
                      getPopupContainer={triggerNode => triggerNode.parentNode}>
                      {contractLocationList.map((option) => {
                        return <Option key={option.code}>{option.name}</Option>
                      })}
                    </Select>
                  )}
                </FormItem>
              )}
            </div>
          )}
          {(formType === 2005 || formType === 2006) &&
          <div>
            <FormItem {...formItemLayout} label={messages('setting.key601'/*报销单还款*/)}>
              {getFieldDecorator('associatePayExpense', {
                valuePropName: 'checked',
                initialValue: true
              })(
                <Switch disabled={form.fromType == 2 && !this.props.tenantMode}/>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={messages('setting.key602'/*关联申请单*/)}>
              <div>
                <div>
                  <div style={{color: '#989898'}}>{messages('setting.key603'/*借款单创建时，可关联申请单*/)}</div>
                  <RadioGroup disabled={form.fromType == 2 && !this.props.tenantMode} value={isHasLoanRelated} onChange={e => this.handleChangeCheckbox(e.target.value, 'isHasLoanRelated')}>
                    <Radio value={false}>{messages('setting.key604'/*不关联*/)}</Radio>
                    <Radio style={{marginLeft: 50}} value={true}>{messages('setting.key605'/*关联*/)}</Radio>
                  </RadioGroup>
                </div>
                {isHasLoanRelated && (
                  <div>
                    <Alert
                      style={{marginBottom: 12}}
                      message={(
                        <span> {messages('setting.key606'/*借款单总金额*/)}
                          <span className='default-color-font'>&nbsp;&le;&nbsp;</span> {messages('setting.key607'/*申请单剩余*/)}
                          "
                          <span className='default-color-font'>{messages('setting.key608'/*可关联金额*/)}</span>
                          "
                        </span>
                      )}
                      type="info"
                      showIcon/>
                    <Row>
                      <Col span={4}>{messages('setting.key2040')/*关联对象*/}</Col>
                      <Col span={19} offset={1}>
                        <Chooser
                          placeholder={messages('common.please.select')}
                          type='available_related_form'
                          labelKey='formName'
                          valueKey='formOID'
                          disabled={relatedFormLoading || (form.fromType == 2 && !this.props.tenantMode)}
                          onChange={value => this.handleSelectForm(value, 'relatedFormList')}
                          value={relatedFormList}
                          listExtraParams={{
                            setOfBooksId: this.context.booksID !== ':booksID' ? this.context.booksID : null,
                            companyOID: !this.props.tenantMode ? this.props.company.companyOID : null
                          }}
                          showNumber={true}
                          single={false}/>
                      </Col>
                    </Row>
                    <Row>
                      <Col span={4} style={{lineHeight: '39px'}}>{messages('setting.key2041')/*关联控制*/}</Col>
                      <Col span={19} offset={1}>
                        <RadioGroup
                          disabled={form.fromType == 2 && !this.props.tenantMode}
                          value={isReference}
                          onChange={e => this.handleChangeCheckbox(e.target.value, 'isReference')}
                        >
                          <Radio value={true}>{messages('setting.key2042')/*关联必填*/}</Radio>
                          <Radio style={{marginLeft: 50}} value={false}>{messages('setting.key2043')/*关联选填*/}</Radio>
                        </RadioGroup>
                      </Col>
                    </Row>
                  </div>
                )}
              </div>
            </FormItem>
          </div>
          }
          {formType === 2006 && (
            <div>
              <FormItem {...formItemLayout} label={messages('setting.key1887')/*关联合同*/}>
                <div>
                  <div style={{color: '#989898'}}>{messages('setting.key1889')/*员工填写借款单时，可关联合同付款计划*/}</div>
                  <RadioGroup disabled={form.fromType == 2 && !this.props.tenantMode} value={contractEnable} onChange={e => this.handleChangeCheckbox(e.target.value, 'contractEnable')}>
                    <Radio value={false}>{messages('setting.key604'/*不关联*/)}</Radio>
                    <Radio style={{marginLeft: 50}} value={true}>{messages('setting.key605'/*关联*/)}</Radio>
                  </RadioGroup>
                </div>
              </FormItem>
            </div>
          )}
          {(formType === 3001 || formType === 3002 || formType === 3003) &&
            <div>
              <FormItem {...formItemLayout} label={messages('setting.key609'/*提交时占用预算*/)}>
                <div className="group-line">
                  <Switch checked={isBudgetEr}
                          disabled={form.fromType == 2 && !this.props.tenantMode}
                          onChange={value => this.handleStatusChange(value, 'isBudgetEr')}/>
                </div>
              </FormItem>
              <FormItem {...formItemLayoutBig} label={messages('setting.key2044')/*可导入结算数据*/}>
                <div className="group-line">
                  <Switch
                    checked={isImportData}
                    disabled={form.fromType == 2 && !this.props.tenantMode}
                    onChange={value => this.handleStatusChange(value, 'isImportData')}
                  />
                  <span className="associate-info">{messages('setting.key2045')/*打开开关，报销单详情显示[导入结算数据]按钮，可导入[结算费用]菜单下的数据。*/}</span>
                </div>
              </FormItem>
            </div>
          }
          {(formType === 3001 || formType === 3002 || formType === 3003) &&
          <div>
            <FormItem {...formItemLayout} label={messages('setting.key1679')/*多付款行*/}>
              <div className="group-line">
                <Switch checked={isMultiLine}
                        disabled={form.fromType == 2 && !this.props.tenantMode}
                        onChange={value => this.handleStatusChange(value, 'isMultiLine')}/>
              </div>
            </FormItem>
            <Row>
              <Col offset={5} span={8}>
                <Alert
                  style={{marginBottom: 12}}
                  message={(
                    <div>
                      <div>{messages('setting.key1680')/*多付款行开启后，填写报销单时可选择除申请人之外的其他付款方及银行账号！*/}</div>
                      <div>{messages('setting.key1681')/*请确保和财务／支付系统的对接使用付款行信息！*/}</div>
                    </div>
                  )}
                  type="info"
                  showIcon/>
              </Col>
            </Row>
            {isMultiLine && (
              <FormItem {...formItemLayout} label={messages('setting.key1761')/*是否允许新增供应商*/}>
                <div className="group-line">
                  <Switch checked={addVenMaster}
                          disabled={form.fromType == 2 && !this.props.tenantMode}
                          onChange={value => this.handleStatusChange(value, 'addVenMaster')}/>
                </div>
              </FormItem>
            )}
          </div>
          }
          {(formType === 3002 || formType === 3003) &&
          <div>
            <FormItem {...formItemLayout} label={messages('setting.key1682')/*新建他人费用*/}>
              <div className="group-line">
                <Switch checked={createOtherExpense}
                        disabled={form.fromType == 2 && !this.props.tenantMode}
                        onChange={value => this.handleStatusChange(value, 'createOtherExpense')}/>
              </div>
            </FormItem>
          </div>
          }
          {(formType === 2001 || formType === 2002) &&
          <div>
            <FormItem {...formItemLayoutBig} label={messages('setting.key609'/*提交时占用预算*/)}>
              <div className="group-line">
                <Switch checked={isBudgetCa}
                        disabled={form.fromType == 2 && !this.props.tenantMode}
                        onChange={value => this.handleStatusChange(value, 'isBudgetCa')}/>
              </div>
            </FormItem>
          </div>
          }
          {(formType === 2001 || formType === 2002) &&
            <div>
              <FormItem {...formItemLayout} label={messages('setting.key1845')/*超申请管控*/}>
                <div className="group-line special-height">
                  <Alert
                    style={{margin: '0 0 12px 0'}}
                    message={messages('setting.key1846')/*开启超申请管控后请勿同时配置拆单！*/}
                    type="info"
                    showIcon
                  />
                  <CheckboxGroup value={controlDimesion} onChange={value => this.handleChangeCheckbox(value, 'controlDimesion')}>
                    <Row>
                      <Col span={8}><Checkbox value={1001}>{messages('setting.key1847')/*总金额管控*/}</Checkbox></Col>
                      <Col span={8}><Checkbox value={1002}>{messages('setting.key1849')/*费用类型管控*/}</Checkbox></Col>
                      <Col span={8}><Checkbox value={1003}>{messages('setting.key2107')/*分摊行管控*/}</Checkbox></Col>
                    </Row>
                  </CheckboxGroup>
                  <Row style={{marginTop: 20}}>
                    <Col span={8}>{messages('setting.key1850')/*控制力度*/}:</Col>
                    <Col span={16}>
                      <RadioGroup value={isForce} onChange={e => this.handleChangeCheckbox(e.target.value, 'isForce')}>
                        <Radio value={0}>{messages('setting.key1073')/*警告*/}</Radio>
                        <Radio value={1}>{messages('setting.key38')/*禁止*/}</Radio>
                      </RadioGroup>
                    </Col>
                  </Row>
                  <Row style={{marginTop: 20}}>
                    <Col span={8}>{messages('setting.key2108')/*容差管控*/}:</Col>
                    <Col span={16}>
                      <span>{messages('setting.key1848')/*允许超过(%)*/}&nbsp;</span>
                      <InputNumber
                        style={{display: 'inline-block', width: 100}}
                        value={overflowProportion}
                        onChange={num => this.handleChangeAmount(num, 'overflowProportion')}
                        min={0}
                        precision={2}
                      />
                    </Col>
                  </Row>
                </div>
              </FormItem>
            </div>
          }
          {(formType === 2001 || formType === 2002) &&
          <div>
            <FormItem {...formItemLayoutBig} label={messages('setting.key1683')/*转交给他人*/}>
              <div className="group-line">
                <Switch checked={isDeliverOther}
                        disabled={form.fromType == 2 && !this.props.tenantMode}
                        onChange={value => this.handleStatusChange(value, 'isDeliverOther')}/>
              </div>
            </FormItem>
          </div>
          }
          {/*日常报销单3001，差旅报销单3002，费用报销单3003*/}
          {(formType === 3001 || formType === 3002 || formType === 3003) && !(form.fromType === 2 && !this.props.tenantMode) && (
            <FormItem {...formItemLayout} label={messages('setting.key610'/*是否添加补贴费用*/)}>
              <div style={{color: '#989898'}}>{messages('setting.key611'/*报销单中直接添加补贴费用*/)}</div>
              <RadioGroup value={withSubsidies} onChange={e => this.handleChangeCheckbox(e.target.value, 'withSubsidies')}>
                <Radio value={false}>{messages('common.no')/*否*/}</Radio>
                <Radio style={{marginLeft: 50}} value={true}>{messages('common.yes')/*是*/}</Radio>
              </RadioGroup>
              {(formType === 3001 || formType === 3002 || formType === 3003) && withSubsidies && (
                <div>
                  <Chooser placeholder={messages('common.please.select')}
                           type='available_travel_rule'
                           labelKey='formName'
                           valueKey='formOID'
                           onChange={this.handleSelectTravelRule}
                           value={selectedFormList}
                           listExtraParams={{
                             setOfBooksId: this.context.booksID !== ':booksID' ? this.context.booksID : null,
                             companyOID: !this.props.tenantMode ? this.props.company.companyOID : null
                           }}
                           showNumber={true}
                           single={true}/>
                  <div style={{lineHeight: '31px', marginTop: 12}}>
                    <span style={{color: '#000000', opacity: .85}}>{messages('setting.key612'/*启用时间*/)}</span>
                    <span style={{color: '#989898'}}>&nbsp;&nbsp;&nbsp;{messages('setting.key613'/*差旅往返日期是否启用时间*/)}</span>
                  </div>
                  <RadioGroup value={withTime} onChange={e => this.handleChangeCheckbox(e.target.value, 'withTime')}>
                    <Radio value={false}>{messages('common.no')/*否*/}</Radio>
                    <Radio style={{marginLeft: 50}} value={true}>{messages('common.yes')/*是*/}</Radio>
                  </RadioGroup>
                </div>
              )}
              {(formType === 3002 || formType === 3003) && withSubsidies && (
                <div>
                  <div style={{lineHeight: '31px', marginTop: 12}}>
                    <span style={{color: '#000000', opacity: .85}}>{messages('setting.key1684')/*添加他人差补*/}</span>
                  </div>
                  <RadioGroup value={newOthersSubsidy} onChange={e => this.handleChangeCheckbox(e.target.value, 'newOthersSubsidy')}>
                    <Radio value={false}>{messages('common.no')/*否*/}</Radio>
                    <Radio style={{marginLeft: 50}} value={true}>{messages('common.yes')/*是*/}</Radio>
                  </RadioGroup>
                </div>
              )}
              {(formType === 3001 || formType === 3002 || formType === 3003) && withSubsidies && (
                <div>
                  <div style={{lineHeight: '31px', marginTop: 12}}>
                    <span style={{color: '#000000', opacity: .85}}>{messages('setting.key2109')/*[补贴计算]中显示大行程*/}</span>
                  </div>
                  <RadioGroup value={notShowItinerary} onChange={e => this.handleChangeCheckbox(e.target.value, 'notShowItinerary')}>
                    <Radio value={true}>{messages('common.no')/*否*/}</Radio>
                    <Radio style={{marginLeft: 50}} value={false}>{messages('common.yes')/*是*/}</Radio>
                  </RadioGroup>
                </div>
              )}
            </FormItem>
          )}
          {(formType === 2001 || formType === 2002) &&
          <div className="special-height">
            <FormItem {...formItemLayout} label={messages('setting.key2046')/*申请单可被借款次数*/}>
              <RadioGroup disabled={form.fromType == 2 && !this.props.tenantMode} value={isLoanRelatedMore} onChange={e => this.handleChangeCheckbox(e.target.value, 'isLoanRelatedMore')}>
                <Radio value='Y'>{messages('setting.key1488')/*多次*/}</Radio>
                <Radio style={{marginLeft: 50}} value='N'>{messages('setting.key1489')/*一次*/}</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem {...formItemLayout} label={messages('setting.key1487')/*申请单可被报销次数*/}>
              <RadioGroup disabled={form.fromType == 2 && !this.props.tenantMode} value={isRelatedMore} onChange={e => this.handleChangeCheckbox(e.target.value, 'isRelatedMore')}>
                <Radio value='Y'>{messages('setting.key1488')/*多次*/}</Radio>
                <Radio style={{marginLeft: 50}} value='N'>{messages('setting.key1489')/*一次*/}</Radio>
              </RadioGroup>
            </FormItem>
          </div>
          }
          {(formType === 2001 || formType === 2002) &&
          <div className="special-height">
            <FormItem {...formItemLayout} label={messages('setting.key1723')/*报销关联多申请*/}>
              <RadioGroup disabled={form.fromType == 2 && !this.props.tenantMode} value={isRelatedNum} onChange={e => this.handleChangeCheckbox(e.target.value, 'isRelatedNum')}>
                <Radio value='Y'>{messages('common.yes')/*是*/}</Radio>
                <Radio style={{marginLeft: 50}} value='N'>{messages('common.no')/*否*/}</Radio>
              </RadioGroup>
            </FormItem>
            <Row>
              <Col offset={5} span={8}>
                <Alert
                  style={{marginBottom: 12}}
                  message={(
                    <div> {messages('setting.key1688')/*开启关联多申请后，请确保对应的接口已调整完成。*/}
                    </div>
                  )}
                  type="info"
                  showIcon/>
              </Col>
            </Row>
          </div>
          }
          {(formType === 2001 || formType === 2002) &&
            <div>
              <FormItem {...formItemLayout} label={messages('setting.key1762')/*是否需要借款*/}>
                <div>
                  <div style={{color: '#989898'}}>{messages('setting.key1763')/*申请单创建时，同时创建借款单*/}</div>
                  <RadioGroup disabled={form.fromType == 2 && !this.props.tenantMode} value={isAutoLoan} onChange={e => this.handleChangeCheckbox(e.target.value, 'isAutoLoan')}>
                    <Radio value={true}>{messages('common.yes'/*是*/)}</Radio>
                    <Radio style={{marginLeft: 50}} value={false}>{messages('common.no'/*否*/)}</Radio>
                  </RadioGroup>
                </div>
                {isAutoLoan && (
                  <div>
                    <Alert
                      style={{marginBottom: 12}}
                      message={messages('setting.key1830')/*申请单、借款单被分配的公司一致时，才可在创建申请单时，同时创建借款单。*/}
                      type="info"
                      showIcon/>
                    <Chooser placeholder={messages('common.please.select')}
                             type='available_loan_form'
                             labelKey='formName'
                             valueKey='formOID'
                             disabled={autoLoanLoading || (form.fromType == 2 && !this.props.tenantMode)}
                             onChange={value => this.handleSelectForm(value, 'autoLoanList')}
                             value={autoLoanList}
                             listExtraParams={{
                               setOfBooksId: this.context.booksID !== ':booksID' ? this.context.booksID : null,
                               companyOID: !this.props.tenantMode ? this.props.company.companyOID : null,
                               isAll: true,
                               formTypeList: [2005, 2006]
                             }}
                             showNumber={false}
                             single={true}/>
                  </div>
                )}
              </FormItem>
            </div>
          }

          <Row style={{marginTop: 12, marginBottom: 20}}>
            <Col span={8} offset={5}>
              {(form.fromType != 2 || this.props.tenantMode) && (form.visibleLoanTypeScope !== 1004) &&
              <Button htmlType="submit" type="primary" loading={saving}>{messages('common.save')/*保存*/}</Button>
              }
            </Col>
          </Row>

        </Form>
      </div>
    )
  }
}

FormDetailBase.propTypes = {
  handleNew: React.PropTypes.func,
  refreshBase: React.PropTypes.func
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    language: state.main.language,
    languageList: state.login.languageList,
    tenantMode: state.main.tenantMode
  }
}

FormDetailBase.contextTypes = {
  formType: React.PropTypes.any,
  formOID: React.PropTypes.string,
  booksID: React.PropTypes.string,
  form: React.PropTypes.object,
  expenseTypeScope: React.PropTypes.object,
  userScope: React.PropTypes.object,
  propertyList: React.PropTypes.array,
  router: React.PropTypes.object
};

const WrappedFormDetailBase = Form.create()(FormDetailBase);

export default connect(mapStateToProps)(WrappedFormDetailBase)
